package com.cqan.system.service.impl;


import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.mail.SmtpSslServer;
import jodd.util.RandomStringUtil;
import jodd.util.StringTemplateParser;
import jodd.util.StringTemplateParser.MacroResolver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqan.common.Constant;
import com.cqan.service.impl.EntityServiceImpl;
import com.cqan.system.dao.SystemConfigDao;
import com.cqan.system.entity.SystemConfig;
import com.cqan.system.entity.SystemConfig.ConfigType;
import com.cqan.system.service.SystemConfigService;
import com.cqan.util.pool.ObjectCachePool;
import com.google.common.collect.Maps;

@Service("systemConfigService")
public class SystemConfigServiceImpl extends
		EntityServiceImpl<SystemConfig, Long,SystemConfigDao> implements SystemConfigService {

	@Resource(name="objectCachePool")
	private ObjectCachePool<String> pool;
	
	@Override
	@Autowired
	public void setEntityDao(SystemConfigDao entityDao) {
		this.entityDao = entityDao;
	}

	@Override
	public List<SystemConfig> getSystemConfig(long ab, ConfigType type) {
		
		return entityDao.getSystemConfig(ab,type);
	}

	
	@Override
	public void sendNoticeEmail(String e,String username) {
		List<SystemConfig> scs = entityDao.findBy("configType",ConfigType.EMAIL);
		Map<String,String> config = changeConfig(scs);
		String content = config.get(Constant.EMAIL_FIND_PASSWORD_CONTENT);
		StringTemplateParser stp = new StringTemplateParser();
		final String code = RandomStringUtil.random(4, '0','9');
		pool.put(username, code);
		Email email = Email.create()
                .from(config.get(Constant.EMAIL_SERVICE_USERNAME))
                .to(e)
                .subject(config.get(Constant.EMAIL_FIND_PASSWORD_SUBJECT))
                .addHtml(stp.parse(content, new MacroResolver() {
					@Override
					public String resolve(String macroName) {
						return code;
					}
				}));
		SmtpServer smtpServer = new SmtpSslServer(config.get(Constant.EMAIL_SMTP_HOST),config.get(Constant.EMAIL_SERVICE_USERNAME),config.get(Constant.EMAIL_SERVICE_PASSWORD));
		SendMailSession session = smtpServer.createSession();
		session.open();
		session.sendMail(email);
		session.close();
	}
	
	private Map<String,String> changeConfig(List<SystemConfig> scs){
		Map<String,String> map = Maps.newHashMap();
		for (SystemConfig sc : scs) {
			map.put(sc.getKey(),sc.getValue());
		}
		return map;
	}


}
